package com.lxp.project.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.lxp.common.utils.SecurityUtils;
import com.lxp.common.utils.file.FileUploadUtils;
import com.lxp.framework.config.SystemConfig;
import com.lxp.framework.web.domain.AjaxResult;
import com.lxp.framework.web.page.TableDataInfo;
import com.lxp.project.system.domain.SysUpload;
import com.lxp.project.system.mapper.SysUploadMapper;
import com.lxp.project.system.service.ISysUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 附件-公用Service业务层处理
 *
 * @author equipment
 * @date 2020-08-20
 */
@Slf4j
@Service
public class SysUploadServiceImpl implements ISysUploadService {
    @Resource
    private SysUploadMapper sysUploadMapper;

    //获取集合数据
    @Override
    public TableDataInfo getPageList(SysUpload model, TableDataInfo tableSupport) {
        QueryWrapper<SysUpload> queryWrapper = new QueryWrapper<>();
        IPage<SysUpload> iPage = sysUploadMapper.selectPage(new Page<>(tableSupport.getPageNum(), tableSupport.getPageSize()), queryWrapper);
        tableSupport.setCode(com.lxp.common.constant.HttpStatus.SUCCESS);
        tableSupport.setMsg("查询成功");
        tableSupport.setRows(iPage.getRecords());
        tableSupport.setTotal(new PageInfo<>(iPage.getRecords()).getTotal());
        return tableSupport;
    }

    //上传
    @Override
    public AjaxResult upload(SysUpload document, MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error(404, "请选择文件");
        }
        String oName = file.getOriginalFilename();
        if (oName == null) {
            oName = document.getName();
        }
        String ext = oName.lastIndexOf(".") == -1 ? "none" : oName.substring(oName.lastIndexOf(".") + 1);
        String id = UUID.randomUUID().toString();
        String name = oName.lastIndexOf(".") == -1 ? "none" : oName.substring(0, oName.indexOf("."));
        JSONObject jsonObj = new JSONObject();
        try {
            String avatar = FileUploadUtils.upload(SystemConfig.getUploadPath(), file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            jsonObj.put("message", "上传成功");
            jsonObj.put("id", id);
            jsonObj.put("businessid", document.getBusinessid());
            jsonObj.put("imgUrl", avatar);
            SysUpload documentPO = new SysUpload();
            documentPO.setName(name);
            documentPO.setId(id);
            documentPO.setFilesize(file.getSize());
            documentPO.setCreatorid(SecurityUtils.getLoginUser().getUser().getUserId());
            documentPO.setCreatorname(SecurityUtils.getNickName());
            documentPO.setVersion("1");
            documentPO.setBusinessid(document.getBusinessid());
            documentPO.setCreatetime(new Date());
            documentPO.setRemark(document.getRemark());
            documentPO.setFiletype(ext);
            documentPO.setFileurl(avatar);
            sysUploadMapper.insert(documentPO);
            return AjaxResult.success(jsonObj);
        } catch (IOException e) {
            jsonObj.put("code", -1);
            jsonObj.put("message", "上传失败: " + e.getMessage());
            return AjaxResult.error(500, jsonObj.toJSONString());
        }
    }

    //文件删除
    @Override
    public AjaxResult deleteFile(String id) {
        try {
            SysUpload arDocument = sysUploadMapper.selectById(id);
            if (arDocument == null) {
                log.error("下载附件为空-{}", id);
                return AjaxResult.error(404, "文件不存在");
            }
            String fileurl = arDocument.getFileurl();
            fileurl = fileurl.substring(8);
            File file = new File(SystemConfig.getProfile() + fileurl);
            if (file.exists()) {
                boolean delete = file.delete();
                if (delete) {
                    sysUploadMapper.deleteById(id);
                }
            } else {
                sysUploadMapper.deleteById(id);
            }
        } catch (Exception e) {
            AjaxResult.error(500, "删除出错!");
            e.printStackTrace();
        }
        return AjaxResult.success(null);
    }

    //图片查看
    @Override
    public ResponseEntity pictureShow(String id, String filePath) {
        try {
            SysUpload documentPO = sysUploadMapper.selectById(id);
            if (documentPO == null) {
                log.error("下载附件为空-{}", id);
                return null;
            }
            String fileDir = filePath + "/";
            File file = new File(fileDir + documentPO.getFileurl());
            InputStream inputStream = new FileInputStream(file);
            byte[] bytes = readInputStream(inputStream);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setCacheControl(CacheControl.noCache());
            httpHeaders.setPragma("no-cache");
            httpHeaders.setExpires(0L);
            httpHeaders.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void imageShow(String id, String filePath, HttpServletResponse response) throws IOException {
        SysUpload arDocument = sysUploadMapper.selectById(id);
        String fileUrl = filePath + "/" + arDocument.getFileurl().substring(9);
        FileInputStream resourceAsStream = new FileInputStream(new File(fileUrl));
        OutputStream out = null;
        byte[] b = new byte[1024];
        int len = 0;
        try {
            out = response.getOutputStream();
            while ((len = resourceAsStream.read(b)) != -1) {
                out.write(b, 0, len);
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }

    //删除
    @Override
    public AjaxResult deleteById(String id) {
        try {
            sysUploadMapper.deleteById(id);
        } catch (Exception e) {
            AjaxResult.error(500, "删除出错!");
            e.printStackTrace();
        }
        return AjaxResult.success(null);
    }

    //添加
    @Override
    public AjaxResult save(SysUpload model) {
        try {
            sysUploadMapper.insert(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(null);
    }

    //修改
    @Override
    public AjaxResult update(SysUpload model) {
        try {
            sysUploadMapper.updateById(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(null);
    }

    @Override
    public List<SysUpload> getListAll() {
        return sysUploadMapper.selectList(null);
    }

    @Override
    public AjaxResult getListByBusinessId(String filetype, String businessid) {
        QueryWrapper<SysUpload> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("businessid", businessid);
        queryWrapper.eq("remark", filetype);
        return AjaxResult.success(sysUploadMapper.selectList(queryWrapper));
    }

    @Override
    public SysUpload findById(String id) {
        return sysUploadMapper.selectById(id);
    }

    @Override
    public SysUpload findByBusinessId(Long businessid) {
        LambdaQueryWrapper<SysUpload> query=new LambdaQueryWrapper<>();
        query.eq(SysUpload::getBusinessid,businessid);
        return sysUploadMapper.selectOne(query);
    }

    /**
     * 输入流装成字节数组
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    private byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
